package com.skt.manage.controller;

import com.skt.common.annotation.Log;
import com.skt.common.core.controller.BaseController;
import com.skt.common.core.domain.AjaxResult;
import com.skt.common.enums.BusinessType;
import com.skt.common.utils.SecurityUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * AI智能问诊Controller
 *
 * @author skt
 * @date 2024-01-24
 */
@RestController
@RequestMapping("/manage")
@Slf4j
public class OpenAIController extends BaseController {

    @Value("${ai.config.deepseek.apiKey}")
    private String API_KEY;

    @Value("${ai.config.deepseek.baseUrl}")
    private String API_URL;

    private final ExecutorService executorService = Executors.newFixedThreadPool(10);
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取AI回答（GET方法）
     */
    @GetMapping("/chat")
    public AjaxResult getAnswer(@RequestParam String question) {
        try {
            log.info("接收到问题: {}", question);

            // 构建消息列表
      // 构建请求体
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", "deepseek-chat");

List<Map<String, String>> messages = new ArrayList<>();

Map<String, String> systemMessage = new HashMap<>();
systemMessage.put("role", "system");
systemMessage.put("content", "你是一个专业的医疗咨询助手，请用专业且友善的方式回答问题。");
messages.add(systemMessage);

Map<String, String> userMessage = new HashMap<>();
userMessage.put("role", "user");
userMessage.put("content", question);
messages.add(userMessage);

requestBody.put("messages", messages);
requestBody.put("temperature", 0.7);
requestBody.put("max_tokens", 2000);
// 非流式响应
requestBody.put("stream", false);

            // 发送请求到Deepseek
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(API_URL);
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setHeader("Authorization", "Bearer " + API_KEY);
                httpPost.setEntity(new StringEntity(
                        objectMapper.writeValueAsString(requestBody),
                        StandardCharsets.UTF_8
                ));

                try (CloseableHttpResponse response = client.execute(httpPost)) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    JsonNode jsonResponse = objectMapper.readTree(responseBody);

                    String answer = jsonResponse.path("choices")
                            .path(0)
                            .path("message")
                            .path("content")
                            .asText("");

                    if (StringUtils.isEmpty(answer)) {
                        return error("AI回答生成失败");
                    }

                    Map<String, Object> result = new HashMap<>();
                    result.put("content", answer);

                    log.info("AI回答生成成功");
                    return success(result);
                }
            }
        } catch (Exception e) {
            log.error("获取AI回答失败", e);
            return error("获取AI回答失败：" + e.getMessage());
        }
    }

    /**
     * 流式对话（POST方法）
     */
    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chat(@RequestBody ChatRequest chatRequest) {
        SseEmitter emitter = new SseEmitter(-1L);

        executorService.execute(() -> {
            try {
                String question = chatRequest.getMessage();
                log.info("开始流式回答, 问题: {}", question);

        // 构建消息列表
List<Map<String, String>> messages = new ArrayList<>();

Map<String, String> systemMessage = new HashMap<>();
systemMessage.put("role", "system");
systemMessage.put("content", "聚城网络科技有限公司的物业管理助手");
messages.add(systemMessage);

Map<String, String> userMessage = new HashMap<>();
userMessage.put("role", "user");
userMessage.put("content", question);
messages.add(userMessage);


                // 构建请求体
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("model", "deepseek-chat");
                requestBody.put("messages", messages);
                requestBody.put("stream", true);
                requestBody.put("temperature", 0.7);
                requestBody.put("max_tokens", 2000);

                // 发送请求到Deepseek
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost request = new HttpPost(API_URL);
                    request.setHeader("Content-Type", "application/json");
                    request.setHeader("Authorization", "Bearer " + API_KEY);
                    request.setEntity(new StringEntity(
                            objectMapper.writeValueAsString(requestBody),
                            StandardCharsets.UTF_8
                    ));

                    try (CloseableHttpResponse response = client.execute(request);
                         BufferedReader reader = new BufferedReader(
                                 new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {

                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.startsWith("data: ")) {
                                String jsonData = line.substring(6);
                                if ("[DONE]".equals(jsonData)) {
                                    break;
                                }

                                JsonNode node = objectMapper.readTree(jsonData);
                                String content = node.path("choices")
                                        .path(0)
                                        .path("delta")
                                        .path("content")
                                        .asText("");

                                if (!content.isEmpty()) {
                                    emitter.send(content);
                                }
                            }
                        }

                        log.info("流式回答结束");
                        emitter.complete();
                    }
                }
            } catch (Exception e) {
                log.error("处理请求失败", e);
                try {
                    emitter.send(SseEmitter.event()
                            .name("error")
                            .data("处理请求失败: " + e.getMessage()));
                } catch (Exception ex) {
                    log.error("发送错误消息失败", ex);
                } finally {
                    emitter.complete();
                }
            }
        });

        return emitter;
    }

    @Data
    static class ChatRequest {
        private String message;
    }
}
